package com.inexas.cu.client.mvp;

import java.util.*;

public class ObservableImpl implements Observable {
	protected final List<Observer> observers = new ArrayList<Observer>();

	/* (non-Javadoc)
     * @see com.inexas.cu.client.mvp.PmObservable#addObserver(com.inexas.cu.client.mvp.PmObserver)
     */
	public void addObserver(Observer observer) {
		assert observer != null : "Null observer";
		assert !observers.contains(observer) : "Duplicate observer";

		observers.add(observer);
	}

	/* (non-Javadoc)
     * @see com.inexas.cu.client.mvp.PmObservable#unobserve(com.inexas.cu.client.mvp.PmObserver)
     */
	public void removeObserver(Observer observer) {
		if(!observers.remove(observer)) {
			throw new RuntimeException("Observer not found");
		}
	}

	/* (non-Javadoc)
     * @see com.inexas.cu.client.mvp.PmObservable#fire(com.inexas.cu.client.mvp.Source, com.inexas.cu.client.mvp.Notification)
     */
	public void fire(Source source, Notification notification) {
		assert source != null : "Null source";

		for(final Observer observer : observers) {
			if(!source.equals(observer)) {
				observer.onChanged(source, notification);
			}
		}
	}
	
	public int getObserverCount() {
		return observers.size();
	}

	@Override
    public String toString() {
		return "Observable(" + observers.size() + ')';
    }

}
